<?

// teste

class modelo_dbm_pdo {
    
    public static $qtde_consultas = 0;
    
    protected $host;
    protected $user;
    protected $password;
    protected $db;

    protected $query;
    protected $string_query;
    
    /**
     *
     * @var PDO
     */
    protected $conexao = NULL;

    
    public function __construct($vet_conexao = NULL) {
        if ($vet_conexao != NULL) {
            $this->connect($vet_conexao);
        }
    }

    
    /**
     * @throws PDOException
     */
    public function connect($vet_conexao) {
        $this->host = $vet_conexao[0];
        $this->user = $vet_conexao[1];
        $this->password = $vet_conexao[2];
        $this->db = $vet_conexao[3];
        
        $dsn = "mysql:dbname=$this->db;host=$this->host";

        // throws PDOException
        $this->conexao = new PDO($dsn, $this->user, $this->password);
    }
    
    
    
    
    // TRANSAÇÃO
    public function beginTransaction() {
        $this->conexao->beginTransaction();
    }
    public function commit() {
        $this->conexao->commit();
    }
    public function rollBack() {
        $this->conexao->rollBack();
    }
    
    
    
    
    // CONSULTA SQL
    
    
    /**
     * @throws PDOQueryException
     */
    public function fetch($string_query) {
        self::$qtde_consultas++;
        $this->string_query = $string_query;
        
        if(!$result = $this->conexao->query($string_query)) {
            throw new PDOQueryException($this->conexao->errorInfo());
        }
        
        $fetch = $result->fetch(PDO::FETCH_ASSOC);
        return $fetch;
    }
    
    
    /**
     * @throws PDOQueryException
     */
    public function fetchAll($string_query) {
        self::$qtde_consultas++;
        $this->string_query = $string_query;
        
        if(!$result = $this->conexao->query($string_query)) {
            throw new PDOQueryException($this->conexao->errorInfo());
        }
        
        $fetch = $result->fetchAll(PDO::FETCH_ASSOC);
        return $fetch;
    }
    

    /**
     * @throws PDOQueryException
     */
    public function exec($string_query) {
        self::$qtde_consultas++;
        $this->string_query = $string_query;
        
        if(!$this->conexao->exec($string_query)) {
            $array_error_info = $this->conexao->errorInfo();
            $message_error = $array_error_info[2];
            
            throw new PDOQueryException($message_error . ", QUERY: '" . $this->string_query . "'");
        }
    }
    
    
    
    
    public function getQuery() {
        return $this->string_query;
    }

    public function lastInsertId() {
        return $this->conexao->lastInsertId();
    }
}


/**
 * Erro na consulta SQL PDO
 */
class PDOQueryException extends Exception { }


?>